package com.syqc.monitor.ui.cost

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.luck.picture.lib.entity.LocalMedia
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.AddOilInfoFee
import com.syqc.entity.Exts
import com.syqc.entity.KeyValue
import com.syqc.entity.OilCard
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import com.syqc.utils.TimeUtil
import com.syqc.utils.ToolsUtil
import okhttp3.MultipartBody

class OilViewModel : BaseFeeViewModel() {
    //加油日期
    var update = TimeUtil.instance.getNowTime(true)

    //里程
    var mile = ""

    //油卡ID
    var oilCardNo = ""

    //加油类型
    var oiltype = ""

    //选择油卡序号
    var chooseIndex = 0

    //照片下标
    var photoIndex = 0

    //加油量
    var feeAdd = ""
        set(value) {
            field = value
            oilTotal()
        }

    //单价
    var feePrice = ""
        set(value) {
            field = value
            oilTotal()
        }

    val feeTotalLive = MutableLiveData<String>()

    /** 油量合计 */
    private fun oilTotal() {
        feeTotal =
            (if (feeAdd.isEmpty()) 0.0 else feeAdd.toDouble()) * (if (feePrice.isEmpty()) 0.0 else feePrice.toDouble())
        feeTotalLive.postValue(ToolsUtil.formatTo2F(feeTotal))
    }

    private var oilFeeEntity: String = ""
    private var oilFee: String = ""
    override fun isParamsOk(): Boolean {
        if (carId.isEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return false
        }
        if (oiltype.isEmpty()) {
            toast(R.string.desc_choose_oil_type)
            return false
        }

        if (feeAdd.isEmpty()) {
            toast(R.string.hint_toast_oil_num)
            return false
        }
        if (feePrice.isEmpty()) {
            toast(R.string.hint_toast_price)
            return false
        }
        if (mile.isEmpty()) {
            toast(R.string.hint_toast_mile)
            return false
        }
        if (feeTotal > 999999) {
            toast(R.string.toast_total_over)
            return false
        }
        val exts = if (peopleId.isEmpty()) "" else GsonUtil.toJson(Exts(peopleId))
        val entity = AddOilInfoFee(
            carId,
            update,
            remark,
            ToolsUtil.formatTo2F(feeTotal),
            feeAdd,
            mile,
            oiltype,
            feePrice,
            oilCardNo,
            exts
        )

        oilFee = GsonUtil.toJson(entity)
        val repairPhotos = GsonUtil.toJson(carPhotos)
        if ("$oilFee$repairPhotos" == oilFeeEntity && isSuccess) {
            toast(R.string.toast_repeat_same_data)
            return false
        }

        if (!isStill) if (!isOilCardOk()) {
            _cardLive.postValue(true)
            return false
        }
        oilFeeEntity = "$oilFee$repairPhotos"
        return true
    }

    fun uploadOil() {
        if (!isParamsOk()) return
        toastLoading(true)
        val parts = getBodyPartsByPath()
        ServiceHelper.getRepository()
            .updateImgFee(
                "FeeAddOil",
                oilFee.replace("%", "%25"), parts, updateName.toString()
            )
            .autoDispose(this)
            .subscribe({
                toastLoading(false)
                getOilCard()
                isSuccess = true
                resultLive.postValue(true)
            }, {
                isSuccess = false
                toastLoading(false)
                it.message?.run { toast(this) }
                resultLive.postValue(false)
            })
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////
    //照片路径| 加油机照片 | imgOilBefore | 非必填项 |
    //| 仪表台照片 | imgOilAfter | 非必填项 |
    //| 票据照片 | imgTicket | 非必填项 |
    private val carPhotos = arrayListOf("", "", "")
    private val photoType = arrayListOf("\"imgOilBefore\"", "\"imgOilAfter\"", "\"imgTicket\"")
    private val updateName = arrayListOf<String>()
    val photoOilLive = MutableLiveData<ArrayList<String>>()

    /**
     * 移除图片
     *
     * @param position
     */
    fun removeIndexPhoto(position: Int) {
        photoIndex = position
        carPhotos[position] = ""
    }

    override fun handlePhoto(medias: ArrayList<LocalMedia>?) {
        medias?.run {
            carPhotos[photoIndex] = this[0].path
            photoOilLive.postValue(carPhotos)
        }
    }


    private fun getBodyPartsByPath(): ArrayList<MultipartBody.Part?>? {
        updateName.clear()
        if (carPhotos.isEmpty()) return null
        val parts = ArrayList<MultipartBody.Part?>()
        for ((index, path) in carPhotos.withIndex()) {

            if (path.isNotEmpty()) {
                val name = photoType[index]
                updateName.add(name)
                parts.add(ToolsUtil.getPartByPath("files", "fee_pic_$index", path))
            }
        }
        return parts
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////
    private val _cardLive = MutableLiveData<Boolean>()
    val cardLive: LiveData<Boolean> = _cardLive
    var isStill = false
    private val keyValues = arrayListOf<KeyValue>()
    private var oilCards = arrayListOf<OilCard>()
    private var oilCard: OilCard? = null
    private var cardIndex: Int? = null

    fun setChooseOilCard(index: Int) {
        cardIndex = index
        oilCard = oilCards[index]
    }

    private fun isOilCardOk(): Boolean {
        if (oilCard == null) return true
        return feeTotal <= oilCard!!.price.toDouble()
    }

    /**
     *获取油卡
     */
    fun getOilCard() {
        toastLoading(true)
        ServiceHelper.getRepository().getOilCard().autoDispose(this).subscribe({
            toastLoading(false)
            oilCards.clear()
            oilCards.addAll(it)
            keyValues.clear()
            it.forEach { card ->
                keyValues.add(KeyValue(card.oilCardNo, card.oilCardNo))
            }
            if (oilCard != null && cardIndex != null) {
                oilCard = oilCards[cardIndex!!]
            }
        }, {
            toastLoading(false)
        })
    }

    fun getKVs() = keyValues

    /////////////////////////////////////加油类型//////////////////////////////////////////////////////
    //加油类型下标
    var oilIndex = 0

    //经办人
    var peopleId = ""
    var peopleName = ""
    private val oilTypes = mutableListOf<KeyValue>()

    init {
        initOilTypes()
        photoOilLive.postValue(carPhotos)
    }

    private fun initOilTypes() {
        oilTypes.add(KeyValue("92#", "92#"))
        oilTypes.add(KeyValue("95#", "95#"))
        oilTypes.add(KeyValue("98#", "98#"))
        oilTypes.add(KeyValue("柴油", AppContext.getDescById(R.string.desc_type_oil_cy)))
    }

    fun getOilTypes() = oilTypes

    override fun clearData() {
        super.clearData()
        //油卡ID
        oilCardNo = ""
        chooseIndex = 0
        oilCard = null
        oilIndex = 0
        oiltype = ""
        peopleId = ""
        peopleName = ""
        (0..<carPhotos.size).forEach {
            carPhotos[it] = ""
        }
        photoOilLive.postValue(carPhotos)
    }


}